package com.ulook.lookplanet.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.qmuiteam.qmui.widget.QMUIFloatLayout;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.base.WidgetData;
import com.ulook.lookplanet.common.AppServer;
import com.ulook.lookplanet.data.model.TArtPic;
import com.ulook.lookplanet.data.model.TTopic;
import com.ulook.lookplanet.ui.notifications.UserDetail.UserDetailActivity;
import com.ulook.lookplanet.ui.square.VArticlePreInfo;
import com.ulook.lookplanet.ui.square.article.ArticleActivity;
import com.ulook.lookplanet.util.StringUtil;
import com.ulook.lookplanet.util.ThrowException;
import com.ulook.lookplanet.util.json.JacksonUtil;
import com.ulook.lookplanet.util.net.AsynRequestUtil;
import com.ulook.lookplanet.util.net.OkHttpException;
import com.ulook.lookplanet.util.net.RequestParams;
import com.ulook.lookplanet.util.net.ResponseByteCallback;
import com.ulook.lookplanet.util.net.ResponseCallback;

import java.io.File;
import java.util.List;

/**
 * 描述：
 *
 * @author L1998
 * @data 2021/4/16
 */
public class ArticleView extends LinearLayout implements WidgetData<VArticlePreInfo> {

    private Context context;
    private VArticlePreInfo articlePreInfo;
    private int currUserID;
    private int imageWidth;

    private QMUIRadiusImageView2 userHeadImg;
    private QMUIFloatLayout topicLayout;
    private AudioPlayerLayout audioPlayerLayout;
    private QMUIFloatLayout imageLayout;
    private ImageButton likeBt;
    private ImageButton collectBt;

    public ArticleView(Context context) {
        super(context);
        initArticleView(context);
    }

    public ArticleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initArticleView(context);
    }

    public ArticleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initArticleView(context);
    }

    /**
     * 初始化组件
     * @param context
     */
    private void initArticleView(Context context){
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.widget_article_view, this, true);

        userHeadImg = findViewById(R.id.w_art_author_img);
        topicLayout = findViewById(R.id.w_art_topic_layout);
        audioPlayerLayout = findViewById(R.id.w_art_audio_layout);
        imageLayout = findViewById(R.id.w_art_image_layout);

    }

    /**
     * 设置帖子信息
     */
    @Override
    public void setWidgetData(VArticlePreInfo value) {
        setWidgetData(value, 0);
    }

    /**
     * 设置帖子信息
     */
    @Override
    public void setWidgetData(VArticlePreInfo articlePreInfo, int currUserID){
        this.articlePreInfo = articlePreInfo;
        this.currUserID = currUserID;

        TextView authorName = findViewById(R.id.w_art_author_name_text);
        if(articlePreInfo.getName() != null){
            authorName.setText(articlePreInfo.getName());
        }
        TextView pubTime = findViewById(R.id.w_art_pub_time_text);
        if(articlePreInfo.getPubtime() != null){
            pubTime.setText(articlePreInfo.getPubtime().subSequence(5, 16));
        }
        TextView content = findViewById(R.id.w_art_content_text);
        if(articlePreInfo.getContent() != null){
            content.setText(articlePreInfo.getContent());
            content.setClickable(true);
            content.setOnClickListener(view -> {
                // 点击跳转详情页面
                gotoDetail();
            });
        }

        // 设置点赞收藏
        initLikeInfo();

        // 获取用户头像
        if(!(articlePreInfo.getHeadimg() == null || "".equals(articlePreInfo.getHeadimg()))){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    byte[] image = (byte[]) res;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);  //使用BitmapFactory工厂，把字节数组转化为bitmap
                    userHeadImg.setImageBitmap(bitmap);
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    ThrowException.print(failuer, failuer.getEmsg());
                }
            };
            AsynRequestUtil.loadImg(AppServer.HEAD_IMG_PATH + articlePreInfo.getHeadimg(), null, callback);
        }else {
            userHeadImg.setImageResource(R.mipmap.user_head_img);
        }
        // 点击头像跳转用户
        userHeadImg.setClickable(true);
        userHeadImg.setOnClickListener(view -> {
            Intent intent = new Intent(context, UserDetailActivity.class);
            intent.putExtra("user", articlePreInfo.getId());
            intent.putExtra("currUser", currUserID);
            context.startActivity(intent);
        });

        // 获取录音
        if(!(articlePreInfo.getAudrofile() == null || "".equals(articlePreInfo.getAudrofile()))){
            String url = AppServer.AUDIO_PATH + articlePreInfo.getAudrofile();
            String dir = context.getExternalCacheDir() + File.separator;
            ResponseByteCallback callback = new ResponseByteCallback() {
                @Override
                public void onSuccess(File file) {
                    audioPlayerLayout.setMediaPath(dir + articlePreInfo.getAudrofile());
                    audioPlayerLayout.setVisibility(VISIBLE);
                }
                @Override
                public void onFailure(String failureMsg) {
                    ThrowException.print(failureMsg);
                }
            };
            AsynRequestUtil.postLoadImg(url, null, dir, articlePreInfo.getAudrofile(), callback);
        }else {
            audioPlayerLayout.setVisibility(GONE);
        }

        // 获取话题
        topicLayout.removeAllViews();   // 清空
        if(articlePreInfo.getHastopic() != 0){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    try {
                        List<TTopic> artPicList = JacksonUtil.json2list((String)res, TTopic.class);
                        if(artPicList != null){
                            for(TTopic tTopic : artPicList){
                                TextView textView = new TextView(context);
                                textView.setText(tTopic.getName());
                                textView.setTextColor(context.getResources().getColor(R.color.light_blue_600));
                                topicLayout.addView(textView);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onFailure(OkHttpException failuer) { }
            };
            RequestParams params = new RequestParams();
            params.put("artId", articlePreInfo.getUid());
            AsynRequestUtil.post(AppServer.ROOT_PATH + "/article/getTopicByComId", params, null, callback);
        }

        // 获取图片
        if(articlePreInfo.getHaspic() != 0){
            RequestParams params = new RequestParams();
            params.put("artid", articlePreInfo.getUid());
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    try {
                        List<TArtPic> artPicList = JacksonUtil.json2list((String)res, TArtPic.class);
                        displayImage(artPicList);
                    } catch (Exception e) {
                        ThrowException.print(e);
                    }
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    ThrowException.print(failuer, failuer.getEmsg());
                }
            };
            AsynRequestUtil.post(AppServer.ROOT_PATH + "/article/getArtPic", params, null, callback);
        }else {
            displayImage(null);
        }
    }

    /**
     * 点击跳转详情
     */
    private void gotoDetail(){
        // 添加浏览记录
        RequestParams params = new RequestParams();
        params.put("userid", currUserID);
        params.put("artid", articlePreInfo.getUid());
        AsynRequestUtil.post(AppServer.ROOT_PATH + "/article/addView", params, null, null);
        // 跳转详情页面
        Intent intent = new Intent(context, ArticleActivity.class);
        intent.putExtra("currUserId", currUserID);
        intent.putExtra("article", articlePreInfo);
        context.startActivity(intent);

    }

    /**
     * 设置点赞收藏
     */
    public void initLikeInfo(){
        // 点赞
        likeBt = findViewById(R.id.w_art_like_bt);
        if(!StringUtil.isEmpty(articlePreInfo.getIslike())){
            likeBt.setImageResource(R.drawable.ic_like_red);
        }else {
            likeBt.setImageResource(R.drawable.ic_like_white);
        }
        likeBt.setOnClickListener(view -> {
            if(currUserID != 0){
                RequestParams params = new RequestParams();
                params.put("userid", currUserID);
                params.put("artid", articlePreInfo.getUid());
                if(articlePreInfo.getIslike() == null || "".equals(articlePreInfo.getIslike())){
                    likeBt.setImageResource(R.drawable.ic_like_red);
                    articlePreInfo.setIslike("1");
                }else {
                    likeBt.setImageResource(R.drawable.ic_like_white);
                    articlePreInfo.setIslike(null);
                    params.put("isCancel", "1");
                }
                AsynRequestUtil.post(AppServer.ROOT_PATH+"/article/like", params, null, null);
            }

        });
        // 收藏
        collectBt = findViewById(R.id.w_art_collect_bt);
        if(!StringUtil.isEmpty(articlePreInfo.getIscollect())){
            collectBt.setImageResource(R.drawable.ic_collection_yellor);
        }else {
            collectBt.setImageResource(R.drawable.ic_collection_white);
        }
        collectBt.setOnClickListener(view -> {
            if(currUserID != 0){
                RequestParams params = new RequestParams();
                params.put("userid", currUserID);
                params.put("artid", articlePreInfo.getUid());
                if(articlePreInfo.getIscollect() == null || "".equals(articlePreInfo.getIscollect())){
                    collectBt.setImageResource(R.drawable.ic_collection_yellor);
                    articlePreInfo.setIscollect("1");
                }else {
                    collectBt.setImageResource(R.drawable.ic_collection_white);
                    articlePreInfo.setIscollect(null);
                    params.put("isCancel", "1");
                }
                AsynRequestUtil.post(AppServer.ROOT_PATH+"/article/collect", params, null, null);
            }

        });
    }

    /**
     * 展示图片
     */
    private void displayImage(List<TArtPic> artPics){
        imageLayout.removeAllViews();
        if(artPics == null){
            return;
        }
        int width = imageLayout.getWidth();
        int size = artPics.size();
        if(size == 1){
            imageWidth = width;
        }else if (size == 2 || size == 4){
            imageWidth = (width - 2) / 2;
        }else {
            imageWidth = (width -2) / 3;
        }
        for(int i = 0; i < size; i++){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    byte[] image = (byte[]) res;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);  //使用BitmapFactory工厂，把字节数组转化为bitmap
                    ImageView imageView = new ImageView(context);
                    imageView.setImageBitmap(bitmap);
                    GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
                    layoutParams.width = imageWidth;
                    layoutParams.height = imageWidth;
                    imageView.setLayoutParams(layoutParams);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageLayout.addView(imageView);
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    ThrowException.print(failuer, failuer.getEmsg());
                }
            };
            AsynRequestUtil.loadImg(AppServer.ARTICLE_IMG_PATH + artPics.get(i).getUid(), null, callback);
        }
    }

}
